package reflect;

import reflect.annotation.AutoRunClass;
import reflect.annotation.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 调用与当前类Test4在同一个包中被注解@AutoRunClass标注的类中所有被@AutoRunMethod标注的方法若干次
 * 次数为@AutoRunMethod上指定的参数
 */
public class Test4 {
    public static void main(String[] args) throws Exception {
        File dir = new File(
                Test4.class.getResource(".").toURI()
        );
        String packName = Test4.class.getPackage().getName();
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File sub : subs){
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cls = Class.forName(packName+"."+className);
            if(cls.isAnnotationPresent(AutoRunClass.class)){
                System.out.println(cls.getName()+"被标注了");
                Object o = cls.newInstance();
                Method[] methods = cls.getDeclaredMethods();
                for(Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        System.out.println(method.getName()+"方法被标注了!");
                        //获取该方法上@AutoRunMethod,并获取到对应的参数值以便调用
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int value = arm.value();
                        for(int i=0;i<value;i++) {
                            method.invoke(o);
                        }
                    }
                }
            }
        }
    }
}
